package com.wangjiawei.controller;

import com.wangjiawei.bean.Message;
import com.wangjiawei.mvc.ResponseBody;
import com.wangjiawei.service.AdminService;
import com.wangjiawei.util.JSONUtil;
import com.wangjiawei.util.UserUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * 2 * @Author: 小王同学
 * 3 * @Date: 2020/10/2 10:28
 * 4
 */
public class AdminController {

    @ResponseBody("/admin/login.do")
    public String login(HttpServletRequest request, HttpServletResponse response){
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        boolean result = AdminService.login(username, password);
        // 准备不同的返回数据
        Message msg = null;
        if (result){
            // {status:0, result:"登录成功"}
            msg = new Message(0, "登录成功");
            // 登录时间和ip的更新
            Date date = new Date();
            String ip = request.getRemoteAddr();
            AdminService.updateLoginTimeAndIp(username, date, ip);
            // 把用户名存到session中
            request.getSession().setAttribute("adminUserName",username);
        }else {
            // {status:-1, result:"登录失败"}
            msg = new Message(-1, "登录失败");
        }
        String json = JSONUtil.toJSON(msg);
        return json;
    }

    @ResponseBody("/admin/logout.do")
    public String logout(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        session.removeAttribute("adminUserName");
        Message msg = new Message();
        msg.setStatus(0);
        msg.setResult("退出成功");
        String json = JSONUtil.toJSON(msg);
        return json;
    }

    @ResponseBody("/admin/getName.do")
    public String getName(HttpServletRequest request, HttpServletResponse response){
        String userName = UserUtil.getUserName(request.getSession());
        Message msg = new Message();
        msg.setStatus(0);
        msg.setResult("查询成功");
        msg.setData(userName);
        String json = JSONUtil.toJSON(msg);
        return json;
    }

}
